<template>
  <button @click="sendBtn()">
    {{ number === 0 ? "发送验证码" : number }}
  </button>
</template>

<script>
import { onUnmounted, ref } from 'vue'

export default {
  setup () {
    const number = ref(0)
    let timer
    const sendBtn = () => {
      if (number.value === 0) {
        number.value = 60
      }
      clearInterval(timer)
      timer = setInterval(() => {
        number.value--
        console.log('定时器正在运行中...')
        if (number.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }

    // 由于定时器是属于 window 对象的，组件卸载后默认不被清理，所以需要自己手动在卸载的钩子函数内部主动清理
    onUnmounted(() => {
      clearInterval(timer)
    })

    return { sendBtn, number }
  }
}
</script>
